//
//  IngredientsViewController.m
//  KeepFit
//
//  Created by Fuzzie Liu on 15/10/28.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "IngredientsViewController.h"

#import "FinalViewController.h"
#import "SouCangViewController.h"
#import "DetailViewController.h"
#import "CategoryViewController.h"
#import "SecondViewController.h"

#import <AFHTTPSessionManager.h>
#import "NetWorkingCache.h"
#import "TopIngredients.h"
#import <UIImageView+WebCache.h>
#import "RGPaperLayout.h"
#import "Topic.h"
#import "TopicCell.h"
# import "UserGuideViewController.h"
#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height

@interface IngredientsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) TopIngredients *firstIng;
@property (nonatomic, strong) NSMutableArray *ingArray;
@property (nonatomic, strong) NSMutableArray *topicArray;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIImageView *headerView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;

@end

@implementation IngredientsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
        //第一次运行
        NSLog(@"第一次运行");
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        UserGuideViewController *userVC = [[UserGuideViewController alloc] init];
        [self presentViewController:userVC animated:YES completion:^{
        }];
    }else{
        NSLog(@"不是第一次运行");
    }
    
    self.navigationController.navigationBar.translucent = NO;
    self.title = @"健康饮食";
    self.index = 0;
    
    [self handleData];
    [self setUpScrollView];
    [self setUpCollectionView];
    [self setUpHeaderView];
    
    UIImage *image = [UIImage imageNamed:@"leftbutton"];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(presentCatgoryVC)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---collectionView的代理方法---
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.topicArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TopicCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    Topic *currentTopic = self.topicArray[indexPath.row];
    [cell.imageView setImage:[UIImage imageNamed:@"back.jpg"]];
    NSURL *imageURL = [NSURL URLWithString:currentTopic.image_url];
    [cell.imageView sd_setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    Topic *selectedTopic = self.topicArray[indexPath.row];
    NSLog(@"%@", selectedTopic.title);
    SecondViewController *secondVC = [[SecondViewController alloc] init];
    secondVC.ID = selectedTopic.ID;
    [self.navigationController pushViewController:secondVC animated:YES];
}
#pragma mark ---scrollView代理方法
//下拉图片放大&&滚动label更换内容
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollView) {
        CGPoint p = scrollView.contentOffset;
//        NSLog(@"%@", NSStringFromCGPoint(p));
        CGRect rect = self.headerView.frame;
        if (p.y < 0) {
            CGFloat newHeight = WIDTH - p.y;
            rect.size.height = newHeight;
            self.headerView.frame = rect;
            self.headerView.layer.frame = rect;
        }
    }else if (scrollView == self.collectionView){
        NSArray *indexArray = [self.collectionView indexPathsForVisibleItems];
        NSIndexPath *indexPath = indexArray[1];
        Topic *topic = self.topicArray[indexPath.row];
        self.titleLabel.text = topic.title;
        self.detailLabel.text = topic.sub_title;
    }
}
// 拖拽结束时变换图片
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView == self.scrollView) {
        // 取出下一张图片
        TopIngredients *nextIng = [self.ingArray objectAtIndex:(self.index + 1) % 11];
        NSURL *url = [NSURL URLWithString:nextIng.image_url];
        [self.headerView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        // 添加动画效果
        CATransition *headerTran = [CATransition animation];
        headerTran.duration = 0.8;
        headerTran.type = kCATransitionFade;
        headerTran.subtype = kCATransitionFromBottom;
        [self.headerView.layer addAnimation:headerTran forKey:nil];
        // 图片换成下一张后记录当前的下标+1
        self.index += 1;
    }
}
// 处理数据
- (void)handleData
{
    // 获取淡入淡出的图片数组
    NSString *string = @"http://food.boohee.com/fb/v1/welcome";
    [NetWorkingCache getUrl:string success:^(id result) {
        NSDictionary *dic = [result objectForKey:@"banner"];
        self.firstIng = [TopIngredients modelWithDic:dic];
        NSArray *list = [result objectForKey:@"others"];
        self.ingArray = [NSMutableArray arrayWithArray:[TopIngredients modelWithArray:list]];
        [self.ingArray insertObject:self.firstIng atIndex:0];
        NSURL *url = [NSURL URLWithString:self.firstIng.image_url];
        [self.headerView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    } failure:^(NSError *error) {
        
    }];
    
    // 获取推荐菜品
    NSString *topicString = @"http://food.boohee.com/fb/v1/topics";
    topicString = [topicString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [NetWorkingCache getUrl:topicString success:^(id result) {
        NSArray *topicsArray = [result objectForKey:@"topics"];
        self.topicArray = [NSMutableArray arrayWithArray:[Topic modelWithArray:topicsArray]];
        
        Topic *firstTopic = self.topicArray.firstObject;
        self.titleLabel.text = firstTopic.title;
        self.detailLabel.text = firstTopic.sub_title;
        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}
#pragma mark ---加载页面---
- (void)setUpScrollView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, WIDTH - 64, WIDTH, self.view.bounds.size.height - WIDTH)];
    [self.view addSubview:_scrollView];
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(WIDTH, self.view.bounds.size.height - WIDTH + 64);
    self.scrollView.showsVerticalScrollIndicator = NO;
    // 创建titleLabel
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];
    [self.scrollView addSubview:_titleLabel];
    self.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    
    // 创建detailLabel
    self.detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 300, 30)];
    [self.scrollView addSubview:_detailLabel];
}
- (void)setUpHeaderView
{
    self.headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -64, WIDTH, WIDTH)];
    self.headerView.contentMode = UIViewContentModeScaleAspectFill;
    self.headerView.alpha = 0.8;
    self.headerView.userInteractionEnabled = YES;
    [self.view addSubview:self.headerView];
    
    UITapGestureRecognizer *tapOnHeader = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnHeader)];
    [self.headerView addGestureRecognizer:tapOnHeader];
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30, WIDTH - 60, WIDTH - 60, 40)];
    [self.headerView addSubview:textField];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.backgroundColor = [UIColor whiteColor];
    textField.textAlignment = NSTextAlignmentCenter;
    textField.placeholder = @"请输入食物名字";
    // 不显示键盘
    textField.inputView = [[UIView alloc] init];
    textField.delegate = self;
    
    UIImageView *scopeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 8, 24, 24)];
    [scopeImageView setImage:[UIImage imageNamed:@"fangdajing"]];
    [textField addSubview:scopeImageView];
    
}
- (void)setUpCollectionView
{
    RGPaperLayout *paperLayout = [[RGPaperLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, WIDTH, self.view.bounds.size.height - WIDTH) collectionViewLayout:paperLayout];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.scrollView addSubview:_collectionView];
    [self.collectionView registerClass:[TopicCell class] forCellWithReuseIdentifier:@"cell"];
    self.collectionView.backgroundColor = [UIColor clearColor];
}
#pragma mark ---跳转页面的方法--
// textField的代理方法, 跳转到搜索页面
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.view endEditing:YES];
    
    SouCangViewController *searchVC = [[SouCangViewController alloc] init];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:searchVC];
    navi.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self.navigationController presentViewController:navi animated:YES completion:nil];
}
// tap手势方法
- (void)tapOnHeader
{
    TopIngredients *ind = self.ingArray[self.index%11];
    
    FinalViewController *finalVC = [[FinalViewController alloc] init];
    finalVC.foodCode = ind.food_code;
    [self.navigationController pushViewController:finalVC animated:YES];
}
// 跳转到类别页面
- (void)presentCatgoryVC
{
    CategoryViewController *categoryVC = [[CategoryViewController alloc] init];
    [self.navigationController pushViewController:categoryVC animated:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
